package com.project.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;

@Controller
public class CheckCodeController {

    @RequestMapping("/checkCode")
    public void getCode(HttpServletResponse response , HttpServletRequest req) throws IOException {
        //设置响应头，表示现在发送给客户端的数据是图片
        response.setContentType("image/jpeg");
        //设置内存图片，大小为130X53
        BufferedImage bf = new BufferedImage(130,53,BufferedImage.TYPE_INT_RGB);

        Graphics2D g = (Graphics2D)bf.getGraphics();

        //设置随机颜色
        Color color = new Color((int)(Math.random()*50+175),(int)(Math.random()*50+175),(int)(Math.random()*50+175));
        //设置背景色
        g.setColor(color);

        g.fillRect(0, 0, 130, 53);

        color = new Color((int)(Math.random()*71+50),(int)(Math.random()*71+50),(int)(Math.random()*71+50));
        //设置前景色
        g.setColor(color);
        //设置字体
        g.setFont(new Font("Times New Roman", Font.BOLD,35));

        StringBuffer sb = new StringBuffer();
        for(int i=0;i<4;i++){
            char r = (char)(Math.random()*26+65);
            sb.append(r);
            g.drawString(String.valueOf(r), 24*i+12, (int)(Math.random()*30+22));
        }

        req.getSession().setAttribute("checkCode",sb.toString());
        //画直线
        g.drawLine(0, 22-(int)(Math.random()*20), 130, (int)(Math.random()*20)+20);
        OutputStream out = response.getOutputStream();

        ImageIO.write(bf, "jpg", out);
    }
}
